/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    void getdes(TreeNode* root)
    {
        if(root == nullptr)
        {
            return;
        }
        getdes(root->left);
        res.push_back(root->val);
        getdes(root->right);
    }
    TreeNode* gettree(int left,int right)
    {
        if(left>right)
        {
            return nullptr;
        }
        int mid = (left+right)/2;
        TreeNode* root = new TreeNode(res[mid]);
        root->left = gettree(left,mid-1);
        root->right = gettree(mid+1,right);
        return root;
    }
    TreeNode* balanceBST(TreeNode* root) {
        //将二叉搜索树变为数组，然后将数组转化为二叉搜索树
        getdes(root);//将二叉搜索树中的值放入到数组中
        return gettree(0,res.size()-1);//将res中的节点转化为平衡二叉树
    }
};